import _ from "lodash";
import { Component, Vue, Prop } from "vue-property-decorator";
import { LOWDB_CONN, LOWDB_GET, LOWDB_SET } from '@/bglib/lowdb_easy';
import { FILE_OPEN_DIALOG, FILE_OPEN, FILE_CLOSE, FILE_READ, IpcFileOpenOption, IpcFileReadOption } from '@/bglib/file_helper';
import { IpcReturnStatus } from '@/plugin/ipc_renderer_ex';


const MYCONFIG_CONN_KEY = "myconfig";
const MYCONFIG_CONN_FILENAME = "myconfig.json";
const MYCONFIG_KEY_TEST_FILE = "test.file";

@Component
export default class FileReader extends Vue {

    public running_msg = "运行信息"
    public file_key = ""
    public file_fullname = ""
    public file_handle = -1

    async created() {
        // 连接配置文件
        let res = await this.$ipcR.send(LOWDB_CONN, {
            key: MYCONFIG_CONN_KEY,
            file: MYCONFIG_CONN_FILENAME
        });
        if (res.status == IpcReturnStatus.success) {
            //console.log(res);
            this.getFileName();
        }
    }

    /**
     * 获取保存的文件名
     */
    private async getFileName() {
        try {
            let { message, value } = await this.$ipcR.send(LOWDB_GET, {
                key: MYCONFIG_CONN_KEY,
                path: MYCONFIG_KEY_TEST_FILE
            });
            this.file_fullname = value;
        } catch ({ status, message }) {
            console.log({ status, message });
        }

    }

    /**
     * 选择文件
     */
    async selectFile() {
        try {
            let { message, value: [file, ...more_files] = [""] } = await this.$ipcR.send(FILE_OPEN_DIALOG, {
                title: "选择文件",
                defaultPath: this.file_fullname,
                filters: [{ name: "所有文件", extensions: ["*"] }],
                properties: ["openFile"]
            })
            this.file_fullname = file;
            let { message: set_message } = await this.$ipcR.send(LOWDB_SET, {
                key: MYCONFIG_CONN_KEY,
                path: MYCONFIG_KEY_TEST_FILE,
                value: file
            });
        } catch ({ status, message }) {
            console.log({ status, message });
        }

    }

    /** 打开文件 */
    async openFile() {
        try {
            let { message, value } = await this.$ipcR.send(FILE_OPEN, {
                path: this.file_fullname,
                flags: "r"
            });
            console.log("openfile: " + message);
            this.file_handle = value || -1;
        } catch ({ status, message }) {
            console.log({ status, message });
        }
    }

    /** 关闭文件 */
    async closeFile() {
        try {
            let { message, value } = await this.$ipcR.send(FILE_CLOSE, {
                fd: this.file_handle
            });
            console.log("closefile: " + message);
            this.file_handle = -1;
        } catch ({ status, message }) {
            console.log({ status, message });
        }
    }

    async readFile() {
        let buffer = await this.readFileData(0, 32);
        console.log("readFile: ", _.join(_.map(buffer, x => _.padStart(x.toString(16), 2, "0")), " "));

    }

    /**
     * 读取数据
     * @param position 读取的起点
     * @param length 读取的长度
     */
    private async readFileData(position: number, length: number) {
        try {
            if (this.file_handle > 0) {
                let {
                    value: { buffer, bytesRead } = { buffer: undefined, bytesRead: 0 }
                } = await this.$ipcR.send(FILE_READ, {
                    fd: this.file_handle,
                    length,
                    position
                } as IpcFileReadOption);
                return buffer || new Uint8Array();
            }
        } catch ({ status, message }) {
            console.log({ status, message });
        }
        return new Uint8Array();
    }

    /**
     * 启动网站服务
     */
    async start() {
        // const res = await this.$ipcR.send(HTTP_BEGIN, { post: this.post });
        // this.is_http_running = true;
        // this.running_msg = res.message;

        // await this.addCss("outcss_01", "out01.css");
    }

    /** 添加样式 */
    async addCss(id: string, path: string) {
        let link = document.createElement("link");
        // let cssEl = document.getElementById(id) as HTMLLinkElement;
        // if (cssEl) {
        //     cssEl.href = `http://localhost:${this.post}/res/css/${path}`;
        // }
        // else {
        //     let head = document.querySelector("head")
        //     if (head) {
        //         let link = document.createElement("link");
        //         link.id = id;
        //         link.rel = "stylesheet";
        //         link.type = "text/css";
        //         link.href = `http://localhost:${this.post}/res/css/${path}`;
        //         head.appendChild(link);
        //     }
        // }
    }

    async stop() {
        // await this.$ipcR.send(HTTP_END);
        // this.is_http_running = false;
    }



    async devTool() {
        // await this.$ipcR.send(DEVTOOL_TOGGLE);
    }

}